package cn.com.shopec.erp.multiChannel.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.taobao.api.DefaultTaobaoClient;
import com.taobao.api.TaobaoClient;
import com.taobao.api.domain.Trade;
import com.taobao.api.internal.util.WebUtils;
import com.taobao.api.request.TradesSoldGetRequest;
import com.taobao.api.response.TradesSoldGetResponse;
import cn.com.shopec.erp.common.constant.SZSCMConstant;
import cn.com.shopec.erp.common.utils.DateUtil;
import cn.com.shopec.erp.common.utils.StringUtil;
import cn.com.shopec.erp.multiChannel.common.MultiChannelConfig;
import cn.com.shopec.erp.multiChannel.common.MultiChannelConstant;
import cn.com.shopec.erp.multiChannel.common.MultiChannelConvert;
import cn.com.shopec.erp.multiChannel.dao.IChannelOrderDao;
import cn.com.shopec.erp.multiChannel.dao.IChannelOrderItemDao;
import cn.com.shopec.erp.multiChannel.dao.IChannelOrderReceiverDao;
import cn.com.shopec.erp.multiChannel.entity.ChannelOrder;
import cn.com.shopec.erp.multiChannel.entity.ChannelOrderItem;
import cn.com.shopec.erp.multiChannel.service.ITaoBaoService;
import net.sf.json.JSONObject;

@Service
public class TaoBaoServiceImpl implements ITaoBaoService {

	private Logger log = Logger.getLogger(JingDongServiceImpl.class);
	
	@Resource
    private IChannelOrderDao channelOrderDao;
	
	@Resource
    private IChannelOrderItemDao channelOrderItemDao;
	
	@Resource
    private IChannelOrderReceiverDao channelOrderReceiverDao;
	
	/**
	 * 获取淘宝授权后accessCode的值
	 * @param request
	 * @param response
	 * @return
	 */
	@Override
	public boolean getAccessTokenByCode(String code) throws Exception {
		  boolean flag=false;
		  String url=MultiChannelConfig.getString("tb.tokenUrl");
	      Map<String,String> props=new HashMap<String,String>();
	      props.put("grant_type",MultiChannelConfig.getString("tb.grantType"));
	      props.put("code",code);
	      props.put("client_id",MultiChannelConfig.getString("tb.client_id"));
	      props.put("client_secret",MultiChannelConfig.getString("tb.client_secret"));
	      props.put("redirect_uri",MultiChannelConfig.getString("tb.redirectUri"));
	      props.put("view",MultiChannelConfig.getString("tb.view"));
	      try{
	    	  //使用淘宝开放平台SDK请求获取授权码
	    	  String jsonText=WebUtils.doPost(url, props, 30000, 30000);
	    	  JSONObject obj = JSONObject.fromObject(jsonText);
			  log.info("obj result is = "+obj);
			  String accessToken = obj.getString("access_token");
	    	  log.info("get resultCode = " + accessToken);
	    	  if(accessToken!=null && !"".equals(accessToken)) {
	  			// 授权码
	  			log.info("jd.accessToken before update：" + MultiChannelConfig.getString("tb.accessToken"));
	  			MultiChannelConfig.setString("tb.accessToken",accessToken);
	  			log.info("jd.accessToken after update ：" + MultiChannelConfig.getString("tb.accessToken"));
	  			log.info("淘宝授权成功");
	  			flag=true;
	  		} else {
	  			// 授权错误
	  			log.info("淘宝授权错误");
	  		}
	      }catch(Exception e){
	          e.printStackTrace();
	      }
		return flag;
	}

	/**
	 * 同步淘宝订单信息
	 * @throws Exception
	 */
	@Override
	@Transactional
	public String syncTBOrderInfo(String startDate, String endDate,String queryType) throws Exception {
		String result=SZSCMConstant.SUCCESS;
		try {
			long pageIndex=(long) MultiChannelConstant.PAGE_INDEX;
			long pageSize=(long) MultiChannelConstant.PAGE_SIZE;
			while(true){
				String serverUrl=MultiChannelConfig.getString("tb.serverUrl");
				String accessToken=MultiChannelConfig.getString("tb.accessToken");
				String appKey=MultiChannelConfig.getString("tb.client_id");
				String appSecret=MultiChannelConfig.getString("tb.client_secret");
				TaobaoClient client = new DefaultTaobaoClient(serverUrl, appKey, appSecret);
				TradesSoldGetRequest req = new TradesSoldGetRequest();
				req.setFields(MultiChannelConstant.TB_OPTIONAL_FIELDS);
				req.setStartCreated(DateUtil.parseTimesTampDate(startDate));
				req.setEndCreated(DateUtil.parseTimesTampDate(endDate));
				req.setStatus(MultiChannelConstant.TB_TRADE_STATE_SEND_GOODS);  //WAIT_SELLER_SEND_GOODS：等待卖家发货
				req.setType(queryType);
				req.setPageNo(pageIndex);
				req.setPageSize(pageSize);
				req.setUseHasNext(true);
				TradesSoldGetResponse rsp = client.execute(req, accessToken);
				log.info("TradesSoldGetResponse result ZhDesc is = "+rsp.getBody()+",code is = "+rsp.getErrorCode());
				if(!StringUtil.isEmpty(rsp.getBody())) {
					// 获得订单数据实体类
					List<Trade> trades = rsp.getTrades();
					if(trades!=null){
						log.info("response trades is = "+trades+",trades result size is = "+trades.size());
						boolean flag=convertAndSaveOrderInfo(trades);
						log.info("convertAndSaveOrderInfo result flag is = "+flag);
						if(!flag){
							result=SZSCMConstant.OPERATION_ERROR;
						}
					}
					//不存在下一页则跳出循环
					if(rsp.getHasNext()){
						pageIndex++;
					}else{
						break;
					}
				}else{
					result=rsp.getSubMsg();
					break;
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		log.info("syncJDOrderInfo result is = "+result);
		return result;
	}
	
	/**
	 * 转换并保存渠道订单信息
	 * @param orderInfos
	 * @return
	 */
	@Override
	@Transactional
	public boolean convertAndSaveOrderInfo(List<Trade> trades){
		boolean flag=false;
		try {
			for (Trade trade : trades) {
				log.info("orderInfo orderId is = "+trade.getTid());
				//没有则新增，存在就修改状态
				ChannelOrder order=channelOrderDao.queryByOrderId(trade.getTid().toString());
				if(order==null){
					channelOrderDao.save(MultiChannelConvert.convertChannelTBOrder(trade));
					List<ChannelOrderItem> items=MultiChannelConvert.convertChannelTBOrderItem(trade);
					for (ChannelOrderItem channelOrderItem : items) {
						channelOrderItemDao.save(channelOrderItem);
					}
					channelOrderReceiverDao.save(MultiChannelConvert.convertChannelTBOrderReceiver(trade));
				}else{
					if(!order.getOrderState().equals(MultiChannelConvert.convertOrderState(trade.getStatus()))){
						order.setOrderState(MultiChannelConvert.convertOrderState(trade.getStatus()));
						channelOrderDao.update(order);
					}
				}
			}
			flag=true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}

}
